package com.water.waterojcodesandbox.codesandbox;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.water.waterojcodesandbox.model.ExecuteCodeRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import com.water.waterojcodesandbox.model.ExecuteMessage;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class JavaDockerCodeSandbox extends JavaCodeSandboxTemplate {

    private static final long TIME_OUT = 60L;

    private static boolean FIRST_INIT = true;

    private static String HAS_CONTAINER_ID = "";


    /**
     * 3、创建容器，把文件复制到容器内
     * @param userCodeFile
     * @param inputList
     * @return
     */
    @Override
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) throws Exception {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        String userCodeParentName = userCodeFile.getParentFile().getName();
        String globalJavaClassPath = userCodeFile.getParentFile().getParentFile().getAbsolutePath();

        // 获取默认的 Docker Client
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();

        // 1. 拉取镜像
        String image = "openjdk:8-alpine";
        log.info("--------------- 1.拉取镜像 ---------------");
        if (FIRST_INIT) {
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    log.info("下载镜像: {}", item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd
                        .exec(pullImageResultCallback)
                        .awaitCompletion();
                log.info("下载镜像完成");
                FIRST_INIT = true;
            } catch (InterruptedException e) {
                log.info("拉取镜像异常");
                throw new RuntimeException(e);
            }
        } else {
            log.info("发现可用镜像: {}", image);
        }

        // 2. 没有初始化容器，创建容器
        log.info("--------------- 2.创建启动容器，并挂载目录 ---------------");
        if (StrUtil.isBlank(HAS_CONTAINER_ID)) {
            CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
            HostConfig hostConfig = new HostConfig();
            // 设置最大运行内存
            hostConfig.withMemory(100 * 1000 * 1000L);
            hostConfig.withMemorySwap(0L);
            hostConfig.withCpuCount(1L);
            // hostConfig.withSecurityOpts(Arrays.asList("seccomp=安全管理配置字符串"));
            // 挂载目录 /tmpCode <=> /app
            hostConfig.setBinds(new Bind(globalJavaClassPath, new Volume("/app")));
            CreateContainerResponse createContainerResponse = containerCmd
                    .withHostConfig(hostConfig)
                    .withNetworkDisabled(true)
                    .withReadonlyRootfs(true)
                    .withAttachStdin(true)
                    .withAttachStderr(true)
                    .withAttachStdout(true)
                    .withTty(true)
                    .exec();
            // 标记容器已经创建，不用重复创建
            HAS_CONTAINER_ID = createContainerResponse.getId();
            log.info("创建容器完成: {}", HAS_CONTAINER_ID);
            // 3.并启动容器
            dockerClient.startContainerCmd(HAS_CONTAINER_ID).exec();
            log.info("启动容器完成: {}", HAS_CONTAINER_ID);
        } else {
            log.info("发现已创建，并启动的容器: {}", HAS_CONTAINER_ID);
        }

        // docker exec keen_blackwell java -cp /app Main 1 3
        // 4.执行命令并获取结果
        log.info("--------------- 3.执行java代码 ---------------");
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsArray = inputArgs.split(" ");
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", String.format("/app/%s", userCodeParentName), "Main"}, inputArgsArray);
            log.info("docker中执行命令: {}", cmdArray);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(HAS_CONTAINER_ID)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};
            long time = 0L;
            // 4.1.判断是否超时
            final boolean[] timeout = {true};
            String execId = execCreateCmdResponse.getId();
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    // 如果执行完成，则表示没超时
                    timeout[0] = false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        log.info("输出错误结果: {}", errorMessage[0]);
                    } else {
                        message[0] = StrUtil.removeAll(new String(frame.getPayload()), "\\n");
                        log.info("输出结果: {}", message[0]);
                    }
                    super.onNext(frame);
                }
            };

            final long[] maxMemory = {0L};

            // 4.2.获取占用的内存
            StatsCmd statsCmd = dockerClient.statsCmd(HAS_CONTAINER_ID);
            ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {

                @Override
                public void onNext(Statistics statistics) {
                    // log.info("内存占用: {}", statistics.getMemoryStats().getUsage());
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }

                @Override
                public void close() throws IOException {

                }

                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }
            });
            // 监听内存占用
            statsCmd.exec(statisticsResultCallback);
            try {
                stopWatch.start();
                dockerClient.execStartCmd(execId)
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.SECONDS);
                stopWatch.stop();
                time = stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                log.info("程序执行异常");
                throw new RuntimeException(e);
            }
            // 超时就抛出错误
            if (timeout[0]) throw new Exception("运行超出时间限制，请不要写卡死程序或进行优化");
            log.info("内存占用: {}", maxMemory[0]);
            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }
        log.info("--------------- 4.打印结果列表---------------");
        log.info("执行结果列表: {}", executeMessageList);
        return executeMessageList;
    }
}



